package genericity;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

class T1 {
    private int n = 1;
    public void t1(int n) {
        this.n = n;
    }
    public void t(int n) {
        this.n = n * 10;
    }

    @Override
    public String toString() {
        return String.valueOf(n);
    }
}

class T2 {
    private int n = 1;
    public void t2(int n) {
        this.n = n;
    }
    public void t(int n) {
        this.n = n * 10;
    }

    @Override
    public String toString() {
        return String.valueOf(n);
    }
}

/**
 * 将一个方法应用到一个列表中
 */
public class Test5 {
    static <T> List<T> generatorList(Class<T> t, int n) throws IllegalAccessException, InstantiationException {
        List<T> list = new ArrayList<>();
        for (int i = 0; i < n; i++)
            list.add(t.newInstance());
        return list;
    }

    static <T, S extends Iterable<? extends T>>
    void apply(S seq, String f, Object... args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        for(T t : seq)
            t.getClass().getDeclaredMethod(f, int.class).invoke(t, args);
    }
    public static void main(String[] args) throws Exception {
        List<T1> t1List = generatorList(T1.class, 10);
        List<T2> t2List = generatorList(T2.class, 10);
        apply(t1List, "t", 1);
        apply(t2List, "t", 2);
        System.out.println(t1List);
        System.out.println(t2List);
    }
}
